package com.zh.chat.gui.lable;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageLabel extends JLabel {

	/**
	 * 自适应图片标签
	 */
	private static final long serialVersionUID = -3600667137055709280L;
	
	private Image image;
	int imgwidth = 0;
	int imgheight = 0;
	/**
	 * 【描 述】：缓冲图片（就是在内存中先画出来的图）
	 * 
	 * @since 2012-1-17 v1.0
	 */
	Image offScreenImage = null;

	public ImageLabel(File file) {
		try {
			Image srcImage = ImageIO.read(file);
			Image temp = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
			temp.getGraphics().drawImage(srcImage, 0, 0, 100, 100, null);
			image = temp;
			this.setLayout(null);
			this.addComponentListener(new ComponentAdapter() {
				@Override
				public void componentResized(ComponentEvent e) {
					super.componentResized(e);
					zoom();
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public ImageLabel(ImageIcon imageIcon) {
		Image srcImage = imageIcon.getImage();
		Image temp = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
		Graphics g = temp.getGraphics();
		g.setColor(Color.LIGHT_GRAY);
		g.fillRect(0, 0, 100, 100);
		g.drawImage(srcImage, 2, 2, 96, 96, null);
		image = temp;
		this.setLayout(null);
		this.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				super.componentResized(e);
				zoom();
			}
		});
	}

	public void zoom() {
		ImageIcon icon = new ImageIcon(image);
		int lastHeight = imgheight;
		int lastWidth = imgwidth;
		imgwidth = this.getWidth()-10;
		imgheight = this.getWidth()-10;
		if (imgheight > 180) {
			imgwidth = 180;
			imgheight = 180;
		}
		if (imgheight < icon.getIconWidth()) {
			imgwidth = icon.getIconWidth();
			imgheight = icon.getIconHeight();
		}
		repaint();
	}

	public void paint(Graphics g) {
		if (offScreenImage == null) {
			offScreenImage = this.createImage(
					(new ImageIcon(image)).getIconWidth(),
					(new ImageIcon(image)).getIconHeight());
		}
		Graphics goffScreen = offScreenImage.getGraphics();
		goffScreen.drawImage(image, 0, 0, null);
		g.clearRect(0, 0, imgwidth, imgheight);// 缩小的时候移除上一幅图片
		g.drawImage(offScreenImage, 0, 0, imgwidth, imgheight, this);
	}
}
